package com.mf.ergate.web.security.provider;

import com.mf.ergate.api.auth.model.dto.UserInfoQueryDto;
import com.mf.ergate.api.auth.model.vo.ResourceInfoVo;
import com.mf.ergate.api.auth.model.vo.UserInfoVo;
import com.mf.ergate.web.domain.enums.generic.AppTypeEnum;
import com.mf.ergate.web.domain.enums.generic.IsEnabledEnum;
import com.mf.ergate.web.domain.enums.generic.IsLockEnum;
import com.mf.ergate.web.domain.model.MenuTree;
import com.mf.ergate.web.security.MfUserDetails;
import com.mf.ergate.web.service.auth.ResourceInfoService;
import com.mf.ergate.web.service.auth.UserInfoService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class DbUserDetailsService implements UserDetailsService {

	public Logger logger = LoggerFactory.getLogger(getClass());
	private final static String KEY_PUBLIC_AUTHORITY = "PUBLIC";

	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private ResourceInfoService resourceInfoService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//根据用户账号查询管理平台用户详细信息
		UserInfoQueryDto userInfoQueryDto = new UserInfoQueryDto();
		userInfoQueryDto.setUserAccount(username);
		List<UserInfoVo> userInfos = userInfoService.selectByCondition(userInfoQueryDto);
		if(CollectionUtils.isEmpty(userInfos)){
			logger.error("账号: {}, 不存在", username);
			return null;
		}
		UserInfoVo userInfo = userInfos.get(0);
		MfUserDetails userDetails = new MfUserDetails();
		userDetails.setUserNo(userInfo.getUniqueNo());
		userDetails.setUserAccount(userInfo.getUserAccount());
		userDetails.setUserName(userInfo.getUserName());
		userDetails.setUserPassword(userInfo.getUserPassword());
		userDetails.setUserAvatar(userInfo.getUserAvatar());
		userDetails.setEnable(Objects.equals(userInfo.getIsEnable(), IsEnabledEnum.YES.getIndex()));
		userDetails.setLocked(Objects.equals(userInfo.getIsLocked(), IsLockEnum.YES.getIndex()));

		//组织资源(未去重)
		List<ResourceInfoVo> resourceInfos = resourceInfoService.selectByAppTypeCodeAndUserNo(AppTypeEnum.APP_MANAGE.getIndex(), userInfo.getUniqueNo());

		// 查询资源内容
		List<GrantedAuthority> authorityList = new ArrayList<>();
		authorityList.add(new SimpleGrantedAuthority(KEY_PUBLIC_AUTHORITY));		//添加公共资源码

		Set<String> resourceCodeSet = new HashSet<>();
		Map<String, MenuTree> treeMap = new LinkedHashMap<>();
		for (ResourceInfoVo item : resourceInfos) {
			//过滤重复
			if(!resourceCodeSet.contains(item.getResourceCode())){
				//菜单
				MenuTree tree = new MenuTree();
				tree.setId(item.getResourceCode());
				tree.setCode(item.getResourceCode());
				tree.setIcon(item.getResourceIcon());
				tree.setName(item.getResourceName());
				tree.setUrl(item.getResourceUrl());
				tree.setParentId(item.getParentResourceCode());
				tree.setOrder(item.getResourceSort() == null ? 0 : item.getResourceSort());
				treeMap.put(item.getResourceCode(), tree);
				//授权
				authorityList.add(new SimpleGrantedAuthority(item.getResourceCode()));
			}
			resourceCodeSet.add(item.getResourceCode());
		}

		if (!treeMap.isEmpty()) {
			for (MenuTree tree : treeMap.values()) {
				String parentCode = tree.getParentId();
				MenuTree parent = treeMap.get(parentCode);
				if (parent != null) {
					parent.addChildMenu(tree);
				}
			}
		}
		userDetails.setMenuTree(treeMap.get(AppTypeEnum.APP_MANAGE.name()));
		userDetails.setAuthorities(authorityList);
		return userDetails;
	}
}
